#include "head.h"

// int sendfd(int sockfd,int fdtosend){
//     struct msghdr hdr;
//     bzero(&hdr,sizeof(hdr));
//     //消息的正文
//     char buf[]="hello";
//     struct iovec iov[1];
//     iov[0].iov_base=buf;
//     iov[0].iov_len=5;
//     hdr.msg_iov=iov;
//     hdr.msg_iovlen=1;
//     //消息控制字段 data 放一个fd 是一个int
//     struct cmsghdr *pcmsg=(struct cmsghdr*)malloc(CMSG_LEN(sizeof(int)));
//     pcmsg->cmsg_len=CMSG_LEN(sizeof(int));
//     pcmsg->cmsg_level=SOL_SOCKET;
//     pcmsg->cmsg_type=SCM_RIGHTS;
//     *(int *)CMSG_DATA(pcmsg)=fdtosend;
//     hdr.msg_control=pcmsg;
//     hdr.msg_controllen=CMSG_LEN(sizeof(int));
//     int ret=sendmsg(sockfd,&hdr,0);
//     ERROR_CHECK(ret,-1,"sendmsg");

//     return 0;
    
// }

int sendfd(int sockfd,int* p,int fdtosend){
    struct msghdr hdr;
    bzero(&hdr,sizeof(hdr));
    //消息的正文
   
    struct iovec iov[1];
    iov[0].iov_base=p;
    iov[0].iov_len=sizeof(*p);
    hdr.msg_iov=iov;
    hdr.msg_iovlen=1;
    //消息控制字段 data 放一个fd 是一个int
    struct cmsghdr *pcmsg=(struct cmsghdr*)malloc(CMSG_LEN(sizeof(int)));
    pcmsg->cmsg_len=CMSG_LEN(sizeof(int));
    pcmsg->cmsg_level=SOL_SOCKET;
    pcmsg->cmsg_type=SCM_RIGHTS;
    *(int *)CMSG_DATA(pcmsg)=fdtosend;
    hdr.msg_control=pcmsg;
    hdr.msg_controllen=CMSG_LEN(sizeof(int));
    int ret=sendmsg(sockfd,&hdr,0);
    ERROR_CHECK(ret,-1,"sendmsg");

    return 0;
    
}

// int recvfd(int pipeFd, int *pFd){
//     struct msghdr hdr;
//     bzero(&hdr,sizeof(struct msghdr));
//     struct iovec iov[1];
//     char buf[6] = {0};//除了数据内容以外，其他和sendmsg是一致的
//     iov[0].iov_base = buf;
//     iov[0].iov_len = 5;//这里一定不能填0
//     hdr.msg_iov = iov;
//     hdr.msg_iovlen = 1;
//     struct cmsghdr *pcmsghdr = (struct cmsghdr *)calloc(1,CMSG_LEN(sizeof(int)));
//     pcmsghdr->cmsg_len = CMSG_LEN(sizeof(int));
//     pcmsghdr->cmsg_level = SOL_SOCKET;
//     pcmsghdr->cmsg_type = SCM_RIGHTS;//SCM->socket-level control message
//     hdr.msg_control = pcmsghdr;
//     hdr.msg_controllen = CMSG_LEN(sizeof(int));
//     int ret = recvmsg(pipeFd,&hdr,0);
//     ERROR_CHECK(ret,-1,"recvmsg");
//     *pFd = *(int *)CMSG_DATA(pcmsghdr);
//     return 0;
// }

int recvfd(int pipeFd,int *flag,int *pFd){
    struct msghdr hdr;
    bzero(&hdr,sizeof(struct msghdr));
    struct iovec iov[1];

    //改动开始
    iov[0].iov_base =flag;
    iov[0].iov_len = sizeof(*flag);//这里一定不能填0
    //改动结束
    
    hdr.msg_iov = iov;
    hdr.msg_iovlen = 1;
    struct cmsghdr *pcmsghdr = (struct cmsghdr *)calloc(1,CMSG_LEN(sizeof(int)));
    pcmsghdr->cmsg_len = CMSG_LEN(sizeof(int));
    pcmsghdr->cmsg_level = SOL_SOCKET;
    pcmsghdr->cmsg_type = SCM_RIGHTS;//SCM->socket-level control message
    hdr.msg_control = pcmsghdr;
    hdr.msg_controllen = CMSG_LEN(sizeof(int));
    int ret = recvmsg(pipeFd,&hdr,0);
    ERROR_CHECK(ret,-1,"recvmsg");
    *pFd = *(int *)CMSG_DATA(pcmsghdr);
    return 0;
}